<template>
  <div style="padding-bottom: 60px;">
    <h3>
      网络部到诊对话分析
    </h3>
    <div style="margin-top: 16px;width: 100%;">
      <Form inline ref="formInline">
        <FormItem>
          <DatePicker v-width="180" v-model="params.date" type="month" placeholder="选择月份" @on-change="changeParamsBtn"
            :clearable="false">
          </DatePicker>
        </FormItem>
        <FormItem>
          <Select v-model="params.department" v-width="180" placeholder="选择部门" @on-change="changeParamsBtn" clearable>
            <Option v-for="(item,index) in departmentList" :key="index" :value="item.value">{{item.label}}</Option>
          </Select>
        </FormItem>
        <FormItem>
          <RadioGroup v-model="params.btn" type="button" @on-change="changeParamsBtn">
            <Radio v-for="(item,index) in btnList" :key="index" :label="item.label"></Radio>
          </RadioGroup>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="exportData">导出</Button>
        </FormItem>
      </Form>
      <template>
        <ux-grid :cell-style="isEdit" :key="reset" border show-overflow ref="plxTable" keep-source max-height="580"
          :data="tableDate" :highlightCurrentRow="false" :edit-config="{trigger: 'click', mode: 'cell'}"
          :show-summary="true" :summary-method="allFun">
          <ux-table-column v-for="(item,index) in columns11" :key="index" :title="item.title"
            :edit-render="item.canEdit" :field="item.children?'':item.key" min-width="100" align="center"
            :fixed="item.fixed">
            <ux-table-column min-width="100" :field="items.children?'':items.key"
              v-for="(items,indexs) in item.children" :key="indexs" :title="items.title" :edit-render="items.canEdit"
              align="center">
              <ux-table-column min-width="100" :field="items1.children?'':items1.key"
                v-for="(items1,indexs1) in items.children" :key="indexs1" :title="items1.title"
                :edit-render="items1.canEdit" align="center">
                <template v-slot:edit="scope">
                  <Input type="number" v-model="scope.row[items1.key]"
                    @on-blur="saveEvent(scope.row,scope,scope.row[items1.key])"
                    @on-focus="getInputFocus($event)"></Input>
                </template>
              </ux-table-column>
              <template v-slot:edit="scope">
                <Input type="number" v-model="scope.row[items.key]"
                  @on-blur="saveEvent(scope.row,scope,scope.row[items.key])" @on-focus="getInputFocus($event)"></Input>
              </template>
            </ux-table-column>
          </ux-table-column>
          </ux-table-column>
        </ux-grid>
      </template>
    </div>
  </div>
</template>
<script>
  import { getReportDepartment, getNetWorkAnalList, setVisitReport, exportCustomerReport } from "@/api/TApi/index.js";
  import Setting from "@/setting";

  export default {
    components: {
    },
    data() {
      return {
        departmentList: [],
        reset: 10,
        tableDate: [],
        btnList: [
          {
            label: "上旬",
            value: 1
          },
          {
            label: "中旬",
            value: 2
          },
          {
            label: "下旬",
            value: 3
          },
          {
            label: "全月",
            value: 0
          },
        ],
        columns11: [],
        isEditData: [],
        params: {
          date: "",
          department: "",
          btn: "",
        }
      };
    },
    methods: {
      getInputFocus(event) {
        event.currentTarget.select();
      },
      allFun({ columns, data }) {
        const means = [] // 合计
        columns.forEach((column, columnIndex) => {
          if (columnIndex === 0) {
            means.push('合计')
          } else {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              means[columnIndex] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              // means[columnIndex] += ' 元'
              // 改变了ele的合计方式，扩展了合计场景
              // 你以为就只有上面这样玩吗？错啦，你还可以自定义样式哦
              // means[columnIndex] = '<span style="color: red">' + means[columnIndex] + '元</span>'
              means[columnIndex] = means[columnIndex]
            } else {
              means[columnIndex] = '';
            }
          }
          if (columnIndex === 8) {//白癜风留电率合计
            means[columnIndex] = (+means[7] === 0 || +means[1] === 0) ? "0%" : ((means[7] / means[1]) * 100).toFixed(2) + "%";
          }
          if (columnIndex === 10) {//白板待查留电率合计
            means[columnIndex] = (+means[9] === 0 || +means[2] === 0) ? "0%" : ((means[9] / means[2]) * 100).toFixed(2) + "%";
          }
          if (columnIndex === 12) {//非白电率合计
            means[columnIndex] = (+means[11] === 0 || +means[3] === 0) ? "0%" : ((means[11] / means[3]) * 100).toFixed(2) + "%";
          }
          if (columnIndex === 14) {//白癜风转化合计
            means[columnIndex] = (+means[13] === 0 || +means[1] === 0) ? "0%" : ((means[13] / means[1]) * 100).toFixed(2) + "%";
          }
          if (columnIndex === 16) {//白板待查转化合计
            means[columnIndex] = (+means[15] === 0 || +means[2] === 0) ? "0%" : ((means[15] / means[2]) * 100).toFixed(2) + "%";
          }
          if (columnIndex === 18) {//非白转化合计
            means[columnIndex] = (+means[17] === 0 || +means[3] === 0) ? "0%" : ((means[17] / means[3]) * 100).toFixed(2) + "%";
          }
        })

        // 返回一个二维数组的表尾合计(不要平均值，你就不要在数组中添加)
        return [means]
      },
      isEdit(a) {
        if (this.isEditData.length) {
          for (let i in this.isEditData) {
            let data = this.isEditData[i]
            if (a._columnIndex === data._columnIndex && a._rowIndex === data._rowIndex) {
              return "color:red"
            }
          }
        }
      },
      exportData() {
        exportCustomerReport({
          department_id: this.params.department,
          date: this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : "",
          monthly_type: this.btnList.filter(ee => ee.label === this.params.btn)[0].value,
        }).then(res => {
          const link = document.createElement('a')
          let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.download = '网络部到诊对话' //下载的文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
        // window.open(`${Setting.apiBaseURL}/v1/customer/report/export-advacement-report?department_id=${this.params.department}&date=${this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : ""}`)
      },
      // 点击保存
      saveEvent(row, scope, num) {
        var reg = /^[0-9]{1}[0-9]*$/;//正整数
        let flag = reg.test(num)
        if (!flag) {
          this.isEditData.push({
            _columnIndex: scope._columnIndex,
            _rowIndex: scope._rowIndex,
          })
          this.$Message.error("请修改为正整数")
          return false
        } else {
          let index = this.isEditData.findIndex(ee => ee._columnIndex === scope._columnIndex && ee._rowIndex === scope._rowIndex)
          if (index !== -1) {
            this.isEditData.splice(index, 1)
          }
        }
        if (!this.isEditData.length) {
          // 判断是否发生改变
          // console.log(this.$refs.plxTable.isUpdateByRow(row))
          // 你也可以不使用这个判断，我是给示例，没做个性化需求
          if (this.$refs.plxTable.isUpdateByRow(row)) {
            // ...保存相关的逻辑（后端的呀，或者前端的呀）
            // 清除表格激活状态
            this.$refs.plxTable.clearActived().then(() => {
              // 局部保存，并将行数据恢复到初始状态（如果 第二个参数record 为空则不改动行数据，只恢复状态）
              // 你不执行这个reloadRow，代表下次进来你上面的这个if还是会执行，不然下次点击保存，还是保存成功哦！状态没改变哦
              this.$refs.plxTable.reloadRow(row, null, null)
              // 如果，假如你保存了后端给你个当前行的row，那么你需要赋值给表格行呢，你就需要把后端给你的row填到第二个参数位置
              // this.$refs.plxTable.reloadRow(row, 后端的row, null)
              // 第三个参数呢就是只改变当前行中的call单个单元格。第三个参数是row中的字段名（field属性的值）
            })
            let params = {
              id: row.id,
              member_id: row.member_id,
              date: this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : "",
              monthly_type: this.btnList.filter(ee => ee.label === this.params.btn)[0].value,
              bdf: row.bdf,
              unknown_bdf: row.unknown_bdf,
              un_bdf: row.un_bdf,
              un_line: row.un_line,
              invalids: row.invalids,
              bdf_call: row.bdf_call,
              unknown_bdf_call: row.unknown_bdf_call,
              un_bdf_call: row.un_bdf_call,
              bdf_visit: row.bdf_visit,
              unknown_bdf_visit: row.unknown_bdf_visit,
              un_bdf_visit: row.un_bdf_visit,
            }
            setVisitReport(params).then(res => {
              // this.$Message.success('保存成功');
            }).finally(() => {
              this._getNetWorkAnalList()
            })
          } else {
            // this.$Message.warning('保存失败，你没改变当前行的数据');
          }
        } else {
          this.$Message.error("请修改为正整数")
        }

      },
      _getNetWorkAnalList() {
        let params = {
          department_id: this.params.department,
          date: this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : "",
          monthly_type: this.btnList.filter(ee => ee.label === this.params.btn)[0].value
        }
        getNetWorkAnalList(params).then(res => {
          this.tableDate = res.map(ee => {
            return {
              ...ee,
              allLine: (+ee.bdf) + (+ee.unknown_bdf) + (+ee.un_bdf) + (+ee.un_line) + (+ee.invalids),//总对话量
              bdf_call_rate: (+ee.bdf_call === 0 || +ee.bdf === 0) ? "0%" : ((+ee.bdf_call) / (+ee.bdf) * 100).toFixed(2) + "%",//白癜风留点率
              unknown_bdf_call_rate: (+ee.unknown_bdf_call === 0 || +ee.unknown_bdf === 0) ? "0%" : ((+ee.unknown_bdf_call) / (+ee.unknown_bdf) * 100).toFixed(2) + "%",//白斑待查留点率
              un_bdf_call_rate: (+ee.un_bdf_call === 0 || +ee.un_bdf === 0) ? "0%" : ((+ee.un_bdf_call) / (+ee.un_bdf) * 100).toFixed(2) + "%",//非白留点率
              bdf_visit_rate: (+ee.bdf_visit === 0 || +ee.bdf === 0) ? "0%" : ((+ee.bdf_visit) / (+ee.bdf) * 100).toFixed(2) + "%",//白癜风转换
              unknown_bdf_visit_rate: (+ee.unknown_bdf_visit === 0 || +ee.unknown_bdf === 0) ? "0%" : ((+ee.unknown_bdf_visit) / (+ee.unknown_bdf) * 100).toFixed(2) + "%",//白斑待查转换
              un_bdf_visit_rate: (+ee.un_bdf_visit === 0 || +ee.un_bdf === 0) ? "0%" : ((+ee.un_bdf_visit) / (+ee.un_bdf) * 100).toFixed(2) + "%",//非白转换
              all_arrive_num: (+ee.bdf_visit) + (+ee.unknown_bdf_visit) + (+ee.un_bdf_visit)
            }
          })
          // this.reset = Math.random() * 100
        })
      },
      // changeParams() {
      //   this._getNetWorkAnalList()
      // },
      changeParamsBtn() {
        this.changeBtn('change')
        this.reset = Math.random() * 100
        this._getNetWorkAnalList()
      },
      _getReportDepartment() {
        getReportDepartment().then((res) => {
          this.departmentList = res;
        });
      },
      changeBtn(type) {
        let canEdit = false
        let time = new Date().getDate()
        let month = new Date().getMonth() + 1
        let month1 = new Date(this.params.date).getMonth() + 1
        if (!type) {
          if (time < 11) {
            this.params.btn = "上旬"
          } else if (time >= 11 && time < 21) {
            this.params.btn = "中旬"
          } else {
            this.params.btn = "下旬"
          }
        }
        let year = new Date().getFullYear()
        let year1 = new Date(this.params.date).getFullYear()
        if (this.params.btn === "全月") {
          canEdit = false
        }
        if (this.params.btn === "上旬" && time <= 11 && month === month1 && year === year1) {
          canEdit = true
        }
        if (this.params.btn === "中旬" && time >= 11 && time <= 21 && month === month1 && year === year1) {
          canEdit = true

        }
        if (this.params.btn === "下旬" && (time >= 21 && month === month1 && year === year1) || (time === 1 && (month - month1 === 1) && year === year1)) {
          canEdit = true
        }
        this.columns11 = [
          {
            title: '姓名',
            key: 'member_name',
            align: 'center',
            minWidth: 120,
            fixed: 'left',
          },
          {
            title: '对话情况',
            align: 'center',
            children: [
              {
                title: '白癜风',
                key: 'bdf',
                align: 'center',
                minWidth: 80,
                canEdit: canEdit,
              },
              {
                title: '白斑待查',
                key: 'unknown_bdf',
                align: 'center',
                minWidth: 80,
                canEdit: canEdit,

              },
              {
                title: '非白',
                key: 'un_bdf',
                align: 'center',
                minWidth: 80,
                canEdit: canEdit,

              },
              {
                title: '3句话掉线量',
                key: 'un_line',
                align: 'center',
                minWidth: 80,
                canEdit: canEdit,

              },
              {
                title: "无效",
                key: 'invalids',
                align: 'center',
                canEdit: canEdit,
                minWidth: 80,
              },
              {
                title: '总对话量',
                key: 'allLine',
                align: 'center',
                minWidth: 80,
              }
            ]
          },
          {
            title: '留电情况',
            align: 'center',
            children: [
              {
                title: '白癜风',
                align: 'center',
                children: [
                  {
                    title: '留电量',
                    key: 'bdf_call',
                    minWidth: 80,
                    align: 'center',
                    canEdit: canEdit,

                  },
                  {
                    title: '留电率',
                    key: 'bdf_call_rate',
                    minWidth: 80,
                    align: 'center',
                  },
                ],

              },
              {
                title: '白斑待查',
                align: 'center',
                children: [
                  {
                    title: '留电量',
                    key: 'unknown_bdf_call',
                    minWidth: 80,
                    align: 'center',
                    canEdit: canEdit,
                  },
                  {
                    title: '留电率',
                    key: 'unknown_bdf_call_rate',
                    minWidth: 80,
                    align: 'center',
                  },
                ],

              },
              {
                title: '非白',
                key: 'un_bdf_call',
                children: [
                  {
                    title: '留电量',
                    key: 'un_bdf_call',
                    minWidth: 80,
                    canEdit: canEdit,
                    align: 'center',
                  },
                  {
                    title: '留电率',
                    key: 'un_bdf_call_rate',
                    minWidth: 80,
                    align: 'center',
                  },
                ],

              },

            ]
          },
          {
            title: '到诊情况',
            align: 'center',
            children: [
              {
                title: '白癜风',
                key: 'bdf_visit',
                children: [
                  {
                    title: '到诊量',
                    key: 'bdf_visit',
                    canEdit: canEdit,
                    minWidth: 80,
                    align: 'center',
                  },
                  {
                    title: '转化',
                    key: 'bdf_visit_rate',
                    minWidth: 80,
                    align: 'center',
                  },
                ],
              },
              {
                title: '白斑待查',
                key: 'unknown_bdf_visit',
                children: [
                  {
                    title: '到诊量',
                    key: 'unknown_bdf_visit',
                    canEdit: canEdit,

                    minWidth: 80,
                    align: 'center',
                  },
                  {
                    title: '转化',
                    key: 'unknown_bdf_visit_rate',
                    minWidth: 80,
                    align: 'center',
                  },
                ],

              },
              {
                title: '非白',
                key: 'un_bdf_visit',
                children: [
                  {
                    title: '到诊量',
                    key: 'un_bdf_visit',
                    canEdit: canEdit,
                    minWidth: 80,
                    align: 'center',
                  },
                  {
                    title: '转化',
                    key: 'un_bdf_visit_rate',
                    minWidth: 80,
                    align: 'center',
                  },
                ],
              },
              {
                title: '总到诊',
                key: 'all_arrive_num',
                minWidth: 80,
              },
            ]
          }
        ]
      },
    },
    created() {
      this.params.date = this.$Date(new Date()).format("YYYY-MM")
      this.changeBtn()
      this._getReportDepartment();
      this._getNetWorkAnalList()
    },
  };
</script>
<style scoped>
  /deep/ input::-webkit-outer-spin-button,
  /deep/ input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }

  /deep/ input[type="number"] {
    -moz-appearance: textfield;
  }
</style>